<template>
  <div>
    <el-container style="background: #f5f7f9;">
      <el-header style="background: #fff;padding: 12px 12px;height:auto;">
        <div>
          <el-form :model="queryData" :inline="true" size="small">
            <el-form-item label="选择客户">
              <el-select v-model="queryData.orgOwner" filterable clearable placeholder="选择客户" @change="queryData.currentPage = 1">
                <el-option v-for="(d, i) in customerOptions" :key="i" :label="d.orgOwnerName" :value="d.orgOwner" />
              </el-select>
            </el-form-item>
            <el-form-item label="批次号">
              <el-input v-model="batchAttribute" type="textarea" :rows="1" style="width: 300px;" placeholder="多个订单号用回车分割,支持批次号、提单号" />
            </el-form-item>
            <el-form-item label="到达仓库时间">
              <el-date-picker
                v-model="queryData.createAtRange"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="list">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main style="margin-top: 15px; background: #fff;padding: 12px 16px 0 16px;height: 100%;">
        <div style="height: 100%;display: flex;">
          <el-button size="small" type="primary" @click="download">导出</el-button>
        </div>
        <el-table
          ref="table"
          :data="table_body"
          border
          :max-height="tableHeight"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="batchNumber" label="批次号" fixed />
          <el-table-column prop="orgOwnerName" label="客户" />
          <el-table-column prop="ba1" label="提单号/柜号" />
          <el-table-column prop="totalCarton" label="总件数" />
          <el-table-column prop="totalCharge" label="应收" />
          <el-table-column prop="totalCost" label="成本" />
          <el-table-column prop="profit" label="利润" />
          <el-table-column prop="arrivedAt" label="到达仓库时间" />
        </el-table>
      </el-main>
      <el-footer style="padding:0;background: #fff;">
        <div style="text-align: right; padding-top: 10px;">
          <el-pagination
            background
            :current-page="queryData.currentPage"
            :page-sizes="pageSizes"
            :page-size="queryData.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageTotal"
            style="float: right;"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-footer>
    </el-container>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import request from '@/utils/request'
export default {
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              picker.$emit('pick', [start, end])
            }
          },
          {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      table_body: [],
      pageTotal: 0,
      multipleSelection: [],
      batchAttribute: '',
      // 分页的数据
      pageSizes: [50, 100, 500],
      total: 0,
      queryData: {
        pageSize: 50,
        currentPage: 1,
        createAtRange: []
      }
    }
  },
  computed: {
    tableHeight() {
      return document.documentElement.clientHeight - 290
    },
    ...mapState(//
      {
        customerOptions: state => state.base.customerOptions
      }
    )
  },
  created() {
    this.list()
  },
  methods: {
    download() {
      const orderNumber = []
      this.multipleSelection.forEach(e => {
        orderNumber.push(e.orderNumber)
      })
      this.queryData.orderId = orderNumber.join('\n')
      if (this.queryData.orgOwner || this.queryData.orderId ||
        (this.queryData.createAtRange && this.queryData.createAtRange.length === 2)) {
        request({
          url: 'batch/report/download',
          data: this.queryData,
          method: 'post'
        }).then(res => {
          this.queryData.orderId = ''
          if (res.success) {
            const link = document.createElement('a')
            const array = this.base64ToUint8Array(res.data)
            const blob = new Blob([array])
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', `提单报表.xlsx`)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
        })
      } else {
        this.$message({
          message: '请先选择条件',
          type: 'error'
        })
      }
    },
    base64ToUint8Array(base64String) {
      const padding = '='.repeat((4 - base64String.length % 4) % 4)
      const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/')
      const rawData = window.atob(base64)
      const outputArray = new Uint8Array(rawData.length)
      for (let i = 0; i < rawData.length; ++i) {
          outputArray[i] = rawData.charCodeAt(i)
      }
      return outputArray
    },
    list() {
      if (this.batchAttribute) {
        this.queryData.batchAttributes = this.batchAttribute.split(/,|\n|，/)
      } else {
        this.queryData.batchAttributes = []
      }
      request({
        url: 'batch/report/query',
        method: 'post',
        data: this.queryData
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.table_body = res.data.records
            this.pageTotal = res.data.total
          }
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      this.queryData.pageSize = val
      this.queryData.currentPage = 1
      this.list()
    },
    handleCurrentChange(val) {
      this.queryData.currentPage = val
      this.list()
    },
    // 多选按钮
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>
